import { getRowByField } from "@/hy_dev_lib/src";
import { Col, Form, Layout, Row } from "antd";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { formItemList } from "../type";
import useFormConfig from "../useFormConfig";
import GragItem from "./GragItem";
import "./index.less";

const { Header, Sider, Content } = Layout;

interface IFormPageProps {
    formConfig: ReturnType<typeof useFormConfig>
    // form: FormInstance; // Form 实例
}
const FormPage = (props: IFormPageProps) => {
    const { formConfig } = props;
    const { formItemsConfig, editingItem, setEditingItem, moveItem } = formConfig
    const [form] = Form.useForm()

    return <DndProvider backend={HTML5Backend}>
        <Content className="page-content form-page">
            <div className="content-header">
                <div className="content-title">页面预览</div>
            </div>
            <div className="content-box">
                <Form
                    labelCol={{ flex: "90px" }}
                    form={form}
                >
                    <Row gutter={16}>
                        {
                            formItemsConfig.map((item, index) => {
                                const { colSpan, name, label, required, type, placeholder } = item;
                                const Component = getRowByField(formItemList, type, "type")?.Component
                                const editing = editingItem?.name === name
                                // TODO: 特殊处理的组件 Checkbox
                                return (
                                    <Col span={colSpan} key={name} onClick={() => setEditingItem(item)} className={`form-item-box ${editing ? "editing" : ""}`}>
                                        <GragItem index={index} moveItem={moveItem} item={{ id: name }}>
                                            <Form.Item
                                                name={name}
                                                label={<label>{label}</label>}
                                                rules={[
                                                    { required: required, message: item.requiredMessage || placeholder || `请输入${label}` }
                                                ]}
                                            >
                                                {/* 这里可以根据type渲染不同的组件 */}
                                                <Component placeholder={placeholder} />
                                            </Form.Item>
                                        </GragItem>
                                    </Col>
                                );
                            })
                        }
                    </Row>
                </Form>
            </div>
        </Content>
    </DndProvider>
};

export default FormPage;
